package com.xuliugen.jwt.demo.service.impl;

import com.xuliugen.jwt.demo.command.LoginCommand;
import com.xuliugen.jwt.demo.dto.UserDTO;
import com.xuliugen.jwt.demo.exception.AuthorizationException;
import com.xuliugen.jwt.demo.exception.UserNotExistedException;
import com.xuliugen.jwt.demo.jwt.JwtHelper;
import com.xuliugen.jwt.demo.mapper.UserMapper;
import com.xuliugen.jwt.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuliugen
 * @date 2018/1/31
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 默认失效时间token 60分钟
     */
    private final static int DEFAULT_EXPIRE_TIME = 1000 * 60 * 60;

    @Override
    public Map<String, Object> login(LoginCommand command) {
        UserDTO record = userMapper.login(command.getUserName());
        if (record == null) {
            throw new UserNotExistedException("用户不存在！");
        }
        //判断用户名密码是否正确
        if (record.getUserPassword().equals(command.getUserPassword())) {
            Map<String, Object> result = new HashMap<>(3);

            //生成token
            Map<String, Object> payload = new HashMap<>(3);
            Date date = new Date();
            //用户ID
            payload.put("uuid", record.getId());
            //生成时间
            payload.put("iat", date.getTime());
            //过期时间1小时
            payload.put("ext", date.getTime() + DEFAULT_EXPIRE_TIME);
            String token = JwtHelper.createToken(payload);

            //封装result
            result.put("token", token);
            record.setUserPassword("");
            result.put("user", record);
            return result;
        } else {
            throw new AuthorizationException("密码错误！");
        }
    }

    @Override
    public List<UserDTO> listUser() {
        return userMapper.listUser();
    }
}
